package com.jse.util.concurrent.old.synchronization;

import java.util.ArrayList;
import java.util.List;

public class SynchronizationTest {
	
	public Counter counter = CounterFactory.newInstance();

	public static void main(String[] args) {
		SynchronizationTest t = new SynchronizationTest();
		t.testCounter();
	}

	public void testCounter() {
		RandomThread ct = null;
		
		List<RandomThread> list = new ArrayList<RandomThread>();
		for (int i = 0; i < 10000; i++) {
			ct = new RandomThread("A" + i);
			// list.add(ct);
			// 启动线程用start。如果用run，其实就是main函数所在线程执行的，新的线程并没有启动
			ct.start();
		}
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("main counter is : " + counter.getValue());
	}
	
	class RandomThread extends Thread {
		public String name;
		
		public RandomThread(String name) {
			this.name = name;
		}
		
		@Override
		public void run() {
			//计数器同步问题，在方法上面加sychronized或者代码块里面用同步块
			counter.increment();
//			try {
//				Thread.sleep(0);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
			System.out.println(counter.getValue());
		}
	}
}
